package com.adcc.foc.core.api;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class XSSFilter  implements Filter {

    FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();//Cookie name
                String value = cookie.getValue();//Cookie value
                int maxAge = cookie.getMaxAge();//Maximum survival time (milliseconds, 0 representative deletion, -1 represents the same as the browser session)
                String path = cookie.getPath();//path
                String domain = cookie.getDomain();//area
                boolean isSecure = cookie.getSecure();//Is there a security protocol?
                StringBuilder buffer = new StringBuilder();
                buffer.append(name).append("=").append(value).append(";");
                if (maxAge == 0) {
                    buffer.append("Expires=Thu Jan 01 08:00:00 CST 1970;");
                } else if (maxAge > 0) {
                    buffer.append("Max-Age=").append(maxAge).append(";");
                }
                if (domain != null) {
                    buffer.append("domain=").append(domain).append(";");
                }
                if (path != null) {
                    buffer.append("path=").append(path).append(";");
                }
                if (isSecure) {
                    buffer.append("secure;");
                }
                buffer.append("HTTPOnly;");
                response.addHeader("Set-Cookie", buffer.toString());
            }
        }
        filterChain.doFilter(new XSSRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }
}
